-- feed_pet
-- Created by chengb Sep/11/2015
-- 成就：冈布奥喂食

-- 内部函数声明
local whenPetUpgradeRank;
local whenGainPet;

-- 注册冈布奥升阶的事件
EventMgr.register("game_achievement/feed_pet", event.UPGRADE_PET_RANK, function(args)
    whenPetUpgradeRank(args);
end);

-- 注册获得冈布奥的事件
EventMgr.register("game_achievement/feed_pet", event.GAIN_PET, function(classId)
    whenGainPet(classId);
end);

-- 注册冈布奥升阶的回调
whenPetUpgradeRank = function(args)
    -- 尝试完成成就
    local classId = args.class_id;
    whenGainPet(classId);
end

-- 获得冈布奥的回调
whenGainPet = function(classId)
    local pet = ME.user.pets[classId];
    if not pet then
        return;
    end

    local curProgress = pet:getRank();

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == GameAchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        local config = GameAchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg["class_id"]) == 'number' and
            ruleArg["class_id"] ~= classId then
            -- 不是需求的冈布奥
            return false;
        end

        return true;
    end

    -- 遍历所有的子规则
    local ids = GameAchievementM.getIdsByRule("pet_rank");
    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            GameAchievementM.setProgress(id, curProgress);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = GameAchievementM.query(id);

        local ruleArg  = config["rule_arg"];
        local progress = config["progress"];
        local desc     = config["desc"];

        desc = string.gsub(desc, "{pet}", PetM.query(ruleArg.class_id, "name"));
        desc = string.gsub(desc, "{0}", progress);

        return desc;
    end,
};